#include "telbook.h"
 
void write_log(char *action)
 {
  time_t rawtime;
  struct tm * timeinfo;
  char time_buffer[80];
  char log[200];

  time ( &rawtime );
  timeinfo = localtime ( &rawtime );

  strftime (time_buffer,80,"%a %d %b %Y %H:%M:%S %Z ",timeinfo);

  sprintf(log, "%s %s %s \n",time_buffer,":",action);


 int fd;
 if((fd = open("logfile",O_WRONLY|O_APPEND,PERMS)) < 0)
  {
    if(errno == ENOENT)
      {
       if((fd = open("logfile",O_WRONLY|O_CREAT|O_EXCL|O_APPEND,PERMS)) < 0)
        {
         if(errno == EEXIST)
          {
            if((fd = open("logfile",O_WRONLY|O_APPEND,PERMS)) < 0)
              {
                 perror("Could not open logfile");
                 exit(0);
              }
            else
             {
                if((write(fd,log,strlen(log)))!=strlen(log))
                  {
                    perror("Failed to write log");
                    exit(0);   
                  }
             }
           }
          else
             {
              perror("Failed to create");
              exit(0);
             }
         }
       else
           {
            if((write(fd,log,strlen(log)))!=strlen(log))
             {
               perror("Failed to write log");
               exit(0);

             }
           }
     }
      else
         {
           perror("Failed to create");
           exit(0);
         }
      }
 else
    {
       if((write(fd,log,strlen(log)))!=strlen(log))
        {
          perror("Failed to write log");
          exit(0);
        }

        }

}
